﻿using System.Data;
using SqlSugar;
using CSRedis;
using SH.Common;

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SH.Order.Domain.OrderClass;
using SH.Common.DataDictionary;


namespace SH.Order.ErrorCodeEnum
{
    public class DbManger
    {

        /// <summary>
        /// 获取业务库对象 （用IOC这块代码不能写到IOC里面）
        /// </summary>
        public static ISqlSugarClient BizDb
        {
            get
            {
                //从Redis中取租户Id
                CSRedisClient _redis = new CSRedisClient(AppService.Configuration["redisIP"]);
                var tenantId = _redis.Get<string>("tenantId");
                var conn = _redis.Get<string>("tenantConn");
                if (string.IsNullOrEmpty(tenantId))
                {
                    conn = string.Empty;
                }
                if (!Db.IsAnyConnection(tenantId))
                {
                    Db.AsTenant().AddConnection(new ConnectionConfig()
                    {
                        ConfigId = tenantId,
                        ConnectionString = conn,
                        DbType = SqlSugar.DbType.MySql,
                        IsAutoCloseConnection = true,
                        MoreSettings = new ConnMoreSettings
                        {
                            IsAutoDeleteQueryFilter = true,//启用删除查询过滤器  
                            IsAutoUpdateQueryFilter = true//启用更新查询过滤器 （表达式更新，如果是实体方式更新建议先查询在更新）
                        }
                    });
                }
                //Db.GetConnection(tenantId).DbMaintenance.CreateDatabase();
                var result = Db.GetConnection(tenantId);
                Type[] types = _redis.Get<Type[]>("orderTypes");
                if (types != null && types.Length > 0)
                {

                }
                else
                {
                    types = typeof(AfterSales).Assembly.GetTypes().Where(it => it.FullName.Contains("SH.Order.Domain.OrderClass")).ToArray();
                    _redis.Set("orderTypes", types);
                    result.CodeFirst.InitTables(types);
                }
                //原理说明
                //IsAnyConnection、AddConnection和GetConnection 都是Scope周期不同请求不会有影响
                //接口过滤器 (继承接口的类都有效) 请升级 5.1.3.47
                result.QueryFilter.AddTableFilter<Tenant>(it => it.TenantId == tenantId);

                return result;
            }
        }
        /// <summary>
        /// 获基础信息库对象 （用IOC这块代码不能写到IOC里面）
        /// </summary>
        public static ISqlSugarClient MasterDb
        {
            get
            {
                //如果是跨服务器分库，也需要动态配置的，因为库的IP会变
                //参考业务库用法
                return Db.GetConnection("default");
            }
        }
        //通过IOC获取注入的Db对象
        public static SqlSugarScope Db
        {
            get
            {
                //如果用Furion就是 App.GetService<ISqlSugarClient>();
                //IOC不会可以看文档： https://www.donet5.com/Doc/27/2563
                var ihttp = AppService.Services.BuildServiceProvider().GetService<IHttpContextAccessor>();
                var obj = ihttp?.HttpContext?.RequestServices.GetService<ISqlSugarClient>();
                return (SqlSugarScope)obj;
            }
        }
    }
}
